package com.example.demo.controller;

import com.example.demo.config.MqttBroker;
import com.example.demo.entity.*;
import com.example.demo.service.CodeAssociationService;
import com.example.demo.service.DeliveryOrderService;
import com.example.demo.service.PurchaseOrderService;
import com.example.demo.service.SerialNumberService;
import com.example.demo.util.GetMessage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/delivery")
@RequiredArgsConstructor
@Component
public class DeliveryOrderController {
    private  final DeliveryOrderService deliveryOrderService;
    private  final PurchaseOrderService purchaseOrderService;
    private  final SerialNumberService serialNumberService;
    private  final CodeAssociationService codeAssociationService;
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/code")
    public GetMessage makeCode (String trainingId,String userId,String packCode,String codeList,String logisticsNumber) throws JsonProcessingException, MqttException {
        DeliveryOrder deliveryOrder=deliveryOrderService.select(trainingId,userId,logisticsNumber,"lcd");
        Map<String,Object> map=new HashMap<>();
        List<String> list=null;
        if(deliveryOrder==null){
            PurchaseOrder purchaseOrder=purchaseOrderService.selectByInfo(userId,trainingId,null,null,"1");
            DeliveryOrder d=new DeliveryOrder();
            d.setDeliveryunit(purchaseOrder.getCompanyname());
            d.setProductname(purchaseOrder.getProductmodel());
            d.setProductnumber(purchaseOrder.getGoodsnumber());
            d.setOutnumber("100");
            d.setPackmodel("KVSP750110");
            d.setPackname("75寸转运木箱01型");
            d.setPacknumber("10");
            d.setTrainingid (trainingId);
            d.setUserid(userId);
            d.setPackidentifys(packCode);
            d.setLogisticsnumber(logisticsNumber);
            d.setType("lcd");
            SerialNumber serialNumber=serialNumberService.select("deliveryOrder");
            if(serialNumber==null){
                list=generateSerialNumbers("00000",10);
                String a=list.get(list.size()-1);
                SerialNumber serialNumber1=new SerialNumber();
                serialNumber1.setSerialnum(a);
                serialNumber1.setUpdatetime(Util.getNowTime());
                serialNumber1.setType("deliveryOrder");
                serialNumberService.save(serialNumber1);
            }else{
                list=generateSerialNumbers(serialNumber.getSerialnum(),10);
                SerialNumber serialNumber1=new SerialNumber();
                serialNumber1.setId(serialNumber.getId());
                serialNumber1.setSerialnum(list.get(list.size()-1));
                serialNumber1.setUpdatetime(Util.getNowTime());
                serialNumberService.updateById(serialNumber1);
            }
//            String ids="";
//            for (String l : list) {
//                ids=ids+"KVS75DBC-BJ01-"+Util.getNowTimeStr()+"-"+l+",";
//            }
            d.setIdentifys(codeList);
            deliveryOrderService.save(d);

        }else{
//            SerialNumber serialNumber=serialNumberService.select("deliveryOrder");
//            list=generateSerialNumbers(serialNumber.getSerialnum(),10);
//            String ids="";
//            for (String l : list) {
//                ids=ids+"KVS75DBC-BJ01-"+Util.getNowTimeStr()+"-"+l+",";
//            }
//            serialNumber.setSerialnum(list.get(list.size()-1));
//            serialNumber.setUpdatetime(Util.getNowTime());
//            serialNumberService.updateById(serialNumber);
//            deliveryOrder.setPackidentifys(deliveryOrder.getPackidentifys()+","+packCode);
//            deliveryOrder.setIdentifys(deliveryOrder.getIdentifys()+ids);
//            deliveryOrder.setOutnumber(String.valueOf(Integer.parseInt(deliveryOrder.getOutnumber())+10));
//            deliveryOrderService.updateById(deliveryOrder);
        }
        map.put("data",codeList);
        String payload = objectMapper.writeValueAsString(map);
        MqttBroker.mqttClient.publish("SendCode/supply/"+userId,new MqttMessage(payload.getBytes(StandardCharsets.UTF_8)));
        return new GetMessage("成功","200","");
    }
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/delivery")
    public GetMessage delivery (String trainingId,String userId,String packCode,String codeList,String logisticsNumber) throws JsonProcessingException, MqttException {
        DeliveryOrder deliveryOrder=deliveryOrderService.select(trainingId,userId,logisticsNumber,"tv");
        Map<String,Object> map=new HashMap<>();
        List<String> list=null;
        if(deliveryOrder==null){
            PurchaseOrder purchaseOrder=purchaseOrderService.selectByInfo(userId,trainingId,null,null,"0");
            DeliveryOrder d=new DeliveryOrder();
            d.setDeliveryunit(purchaseOrder.getCompanyname());
            d.setProductname(purchaseOrder.getProductmodel());
            d.setProductnumber(purchaseOrder.getGoodsnumber());
            d.setPackmodel("KVSP750201");
            d.setPackname("75寸电视包装");
            d.setPacknumber("100");
            d.setTrainingid (trainingId);
            d.setUserid(userId);
            if(packCode==null||codeList==null){
                d.setOutnumber("100");
                CodeAssociation codeAssociation= codeAssociationService.selectByInfo(userId,"tv",trainingId).get(0);
                d.setPackidentifys(codeAssociation.getCodeinfo());
                d.setIdentifys(codeAssociation.getAssociationcode());
            }else{
                d.setPackidentifys(packCode);
                d.setIdentifys(codeList);
            }
            d.setLogisticsnumber(logisticsNumber);
            d.setType("tv");
            deliveryOrderService.save(d);
        }
        return new GetMessage("成功","200","");
    }

    public List<String> getSn(List<String> list){
        List<String> r=new ArrayList<>();
        for (String l : list) {
            r.add("KVS75DBC-BJ01-"+Util.getNowTimeStr()+"-"+l);
        }
        return r;
    }

    public static List<String> generateSerialNumbers(String number, int count) {
        List<String> serialNumbers = new ArrayList<>();
        // 获取输入序列号的长度
        int length = number.length();
        // 将输入的序列号字符串转换为整数，并加 1 作为起始值
        int currentNumber = Integer.parseInt(number) + 1;

        for (int i = 0; i < count; i++) {
            // 格式化当前数字为指定长度的字符串
            String formattedNumber = String.format("%0" + length + "d", currentNumber);
            serialNumbers.add(formattedNumber);
            // 增加当前数字
            currentNumber++;
        }
        return serialNumbers;
    }

    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @PostMapping("/update")
    public GetMessage update (@RequestBody DeliveryOrder deliveryOrder)  {
        boolean bol=deliveryOrderService.updateById(deliveryOrder);
        if(bol){
            return new GetMessage("成功","200","");

        }
        return new GetMessage("失败","500","");
    }
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/select")
    public GetMessage select (String trainingId,String userId,String logisticsNumber,String type)  {
        DeliveryOrder deliveryOrder=deliveryOrderService.select(trainingId,userId,logisticsNumber,type);
        if(deliveryOrder!=null){
            return new GetMessage("成功","200",deliveryOrder);
        }
        return new GetMessage("失败","500","");
    }

}
